package com.zzp.basepresenter.util;

import android.text.TextUtils;

import androidx.annotation.Nullable;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.RequestParams;
import org.xutils.http.body.StringBody;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class XutilParam {
    private static XutilParam instance;

    public static XutilParam getInstance() {
        if (instance == null) {
            synchronized (XutilParam.class) {
                if (instance == null) {
                    instance = new XutilParam();
                }
            }
        }
        return instance;
    }


    public RequestParams makeParams(String url, @Nullable String token, @Nullable HashMap<String, Object> map) {
        RequestParams params = new RequestParams(url);
        params.setConnectTimeout(30000);
        try {
            if (map != null && !map.isEmpty()) {
                params.setRequestBody(new StringBody(getData(map), "UTF-8"));
                params.setBodyContent("application/json");
            }
            if (!TextUtils.isEmpty(token)) {
                params.addHeader("token", token);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return params;
    }

    public String getData(HashMap<String, Object> map) {
        JSONObject object = new JSONObject();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            try {
                object.put(entry.getKey(), entry.getValue());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        LoggerUtils.getInstance().i("request params   " + object.toString());
        return object.toString();
    }


    public String getParamSub(HashMap<String, Object> map) {
        String s = "";
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            s += entry.getKey() + "=" + entry.getValue() + "&";
        }
        s = s.substring(0, s.length() - 1);
        LoggerUtils.getInstance().i("param substring  =  " + s);
        return s;
    }

    public String getData(Map<String, String> map) {
        JSONObject object = new JSONObject();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            try {
                object.put(entry.getKey(), entry.getValue());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return object.toString();
    }
}
